package com.example.demo.leetcode.classics150;

import java.util.Arrays;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _130数字范围按位与
 * @description
 * @date 2023/08/23 16:42
 * <p>
 * ******************************************************
 */
public class _130数字范围按位与 {

    public static int rangeBitwiseAnd(int left, int right) {
        //m 要赋值给 i，所以提前判断一下
        if(left == Integer.MAX_VALUE){
            return left;
        }
        int res = left;
        for (int i = left + 1; i <= right; i++) {
            res &= i;
            if(res == 0 ||  i == Integer.MAX_VALUE){
                break;
            }
        }
        return res;
    }


    public static int rangeBitwiseAnd1(int left, int right) {
        int[] res = new int[32];
        boolean[] confirm = new boolean[32];
        for (int i = left; i <= right; i++) {
            String binaryString = Integer.toBinaryString(i);
            final int length = binaryString.length();
            for (int j = length - 1; j >= 0; j--) {
                int curr = binaryString.charAt(j) - '0';
                if (confirm[32 + j - length]) {
                    continue;
                }
                if (curr == 0) {
                    res[32 + j - length] = 0;
                    confirm[32 + j - length] = true;
                } else {
                    if (i == right) {
                        res[32 + j - length] = 1;
                    }
                }
            }
        }
        StringBuilder result = new StringBuilder();
        for (int re : res) {
            result.append(re);
        }
        return Integer.parseInt(result.toString(), 2);
    }

    public static void main(String[] args) {
        System.out.println(rangeBitwiseAnd(5, 7));
    }

}
